import time
import json
from alg import bubble_sort


def test_algorithm():
    """测试算法正确性和运行时间"""
    with open("test_cases.json") as f:
        test_cases = json.load(f)

    results = []
    for name, case in test_cases.items():
        arr = case["original"].copy()

        # 计时开始
        start_time = time.perf_counter()
        result = bubble_sort(arr)
        elapsed = time.perf_counter() - start_time

        # 验证结果
        is_correct = result == case["expected"]
        results.append(
            {
                "case": name,
                "size": len(arr),
                "correct": is_correct,
                "time_ms": round(elapsed * 1000, 3),
            }
        )

    # 打印测试结果
    print(f"{'Case':<10} | {'Size':<6} | {'Correct':<8} | {'Time(ms)':<10}")
    print("-" * 40)
    for r in results:
        print(
            f"{r['case']:<10} | {r['size']:<6} | {str(r['correct']):<8} | {r['time_ms']:<10}"
        )


if __name__ == "__main__":
    test_algorithm()
